function back() {
    api.closeWin();
}

function openWinto(name, url, val) { //打开新窗口
    if (api.systemType == "ios") {
        var times = 0;
    } else {
        var times = 300;
    }
    api.openWin({
        name: name,
        url: url + '.html',
        delay: times,
        slidBackType: 'edge',
        vScrollBarEnabled: false,
        bounces: false,
        pageParam: {
            name: val
        }
    })
};

function openWinto2(name, url, val) { //打开新窗口
    if (api.systemType == "ios") {
        var times = 0;
    } else {
        var times = 300;
    }
    api.openWin({
        name: name,
        url: url + '.html',
        delay: times,
        slidBackType: 'edge',
        bounces: false,
        vScrollBarEnabled: false,
        pageParam: {
            name: val
        }
    })
};

function showProgress() {
    // api.showProgress();
}

var ajaxUrl = 'http://lv.bii.cn/';
var ajaxUrlapi = 'http://lv.bii.cn/api/';
var ajaxRoute = {
    sms: ajaxUrlapi + "sms/send",
    mobilelogin: ajaxUrlapi + "user/mobilelogin",
    baseinfo: ajaxUrlapi + "user/baseinfo",
    avatarUpload: ajaxUrlapi + "user/avatarUpload",
    verify: ajaxUrlapi + "user/verify",
    finish: ajaxUrlapi + "user/stepfinish",
    agreement: ajaxUrlapi + "user/agreement",
    onlocation: ajaxUrlapi + "user/onlocation",
    center: ajaxUrlapi + "user/center",
    selectnearby: ajaxUrlapi + "meeting/selectnearby",
    gonggaolist: ajaxUrlapi + "user/gonggaolist",
    gonggaodetail: ajaxUrlapi + "user/gonggaodetail",
    share: ajaxUrlapi + "user/share",
    withdraw: ajaxUrlapi + "order/withdraw",
    withdrawlist: ajaxUrlapi + "order/withdrawlist",
    buyvip: ajaxUrlapi + "user/buyvip",
    basesave: ajaxUrlapi + "user/basesave",
    biosave: ajaxUrlapi + "user/biosave",
    makemeeting: ajaxUrlapi + "meeting/make",
    pushinfo: ajaxUrlapi + "push/info",
    location: ajaxUrlapi + "meeting/location",
    lover: ajaxUrlapi + "push/lover",
    accept: ajaxUrlapi + "meeting/accept",
    comment: ajaxUrlapi + "push/comment",
    judge: ajaxUrlapi + "meeting/judge",
    meetingstart: ajaxUrlapi + "meeting/start",
    distance: ajaxUrlapi + "index/distance",
    userdistance: ajaxUrlapi + "user/distance",
    yue: ajaxUrlapi + "user/yue",
    charge: ajaxUrlapi + "pay/charge",
    wxpay: ajaxUrlapi + "pay/wxpay",
    job: ajaxUrlapi + "user/job",
    commentlist: ajaxUrlapi + "user/commentlist",
    infocomment: ajaxUrlapi + "user/infocomment",
    meetingcomment: ajaxUrlapi + "meeting/comment",
    getcustom: ajaxUrlapi + "user/getcustom",
    meetingnearby: ajaxUrlapi + "meeting/nearby",
    userlogin: ajaxUrlapi + "user/login",
    userresetpwd: ajaxUrlapi + "user/resetpwd",
    userregister: ajaxUrlapi + "user/register",
    userispay: ajaxUrlapi + "user/ispay",
    feekback: ajaxUrlapi + "index/feekback",
    userban: ajaxUrlapi + "user/ban",
}

function isLogin() {
    if ($api.getStorage('userInfo')) {
        return true
    } else {
        return false
    }
}


function sendEvent(name) {
    api.sendEvent({
        name: name,
    });
}

function addEvent(name, fn) {
    api.addEventListener({
        name: name
    }, fn);
}

// 跳转登录
function toLogin() {
    if (api.systemType == "ios") {
        var times = 0;
    } else {
        var times = 300;
    }
    api.openWin({ //未登录打开登陆窗口
        name: 'login',
        url: './html/login/login.html',
        delay: times,
        slidBackType: 'edge',
        vScrollBarEnabled: false,
        slidBackEnabled: false,
    })
};

// 获取网页中的图片信息
function cacheDataImg() {
    var that = this;
    var imgs = $api.domAll("img[src][data-cache=no]");
    if (imgs.length > 0) {
        cacheImg(imgs, 0);
    }
};

function cacheDataImg2() {
    var that = this;
    var imgs = $api.domAll("img[src]");
    if (imgs.length > 0) {
        cacheImg(imgs, 0);
    }
};

// 缓存图片
function cacheImg(imgs, index) {
    var that = this
    var el = imgs[index];
    var src = $api.attr(el, "data-src");
    api.imageCache({
        url: src,
        thumbnail: false
    }, function (ret, err) {
        if (ret.status) {
            $api.attr(el, "src", ret.url);
            $api.attr(el, "data-cache", "yes");
        }
        ;
        var nextIndex = ++index;
        if (nextIndex < imgs.length) {
            cacheImg(imgs, nextIndex);
        }
        ;
    });
};

function fnClose() {
    MNActionButton.close();
};

function fnHide() {
    MNActionButton.hide();
};

function fnShow() {
    MNActionButton.show();
};

function isInstalled() {
    wx.isInstalled(function (ret, err) {
        if (ret.installed) {
            alert(JSON.stringify(ret))
        } else {
            alert(JSON.stringify(err))
        }
    });
}

function shareText() {
    wx.shareText({
        apiKey: '',
        scene: 'timeline',
        text: '我分享的文本'
    }, function (ret, err) {
        if (ret.status) {
            alert(JSON.stringify(ret))
        } else {
            alert(JSON.stringify(err))
        }
    });
}

function shareImage(Vscene) {
    wx.shareImage({
        apiKey: '',
        scene: Vscene,
        thumb: 'widget://res/iconfont-touxiang.png',
        contentUrl: "widget://res/8.jpg"
    }, function (ret, err) {
        if (ret.status) {
            alert(JSON.stringify(ret))
        } else {
            alert(JSON.stringify(err))
        }
    });
}

function shareMusic(Vscene) {
    wx.shareMusic({
        apiKey: '',
        scene: Vscene,
        title: '分享音乐',
        description: '分享音乐的描述',
        thumb: 'widget://res/iconfont-touxiang.png',
        musicDataUrl: "http://docs.apicloud.com/test/m.mp3",
        contentUrl: 'http://www.baidu.com'
    }, function (ret, err) {
        if (ret.status) {
            alert(JSON.stringify(ret))
        } else {
            alert(JSON.stringify(err))
        }
    });
}

function shareVideo(Vscene) {
    wx.shareVideo({
        apiKey: '',
        scene: Vscene,
        title: '分享视频',
        description: '分享视频的描述',
        thumb: 'widget://res/iconfont-touxiang.png',
        contentUrl: 'http://www.youku.com/'
    }, function (ret, err) {
        if (ret.status) {
            alert(JSON.stringify(ret))
        } else {
            alert(JSON.stringify(err))
        }
    });
}

function shareWebpage(Vscene) {
    wx.shareWebpage({
        apiKey: '',
        scene: Vscene,
        title: '分享网页的标题',
        description: '分享网页的描述',
        thumb: 'widget://res/iconfont-touxiang.png',
        contentUrl: 'http://www.apicloud.com'
    }, function (ret, err) {
        if (ret.status) {
            alert(JSON.stringify(ret))
        } else {
            alert(JSON.stringify(err))
        }
    });
}

function shareMutableImg() {
    wx.shareMutableImg({
        description: 'weixin share image test description',
        imgs: ['widget://res/girl.png', 'widget://res/8.jpg', 'widget://res/6.jpg']
    });
}

(function () {
    var u = {};
    var appSignNum = 35;
    var host = 'http://wy.bii.cn/'
    var apihost = "http://wy.bii.cn/"
    var defaultRequest = {
        url: host,
        time: parseInt(new Date().getTime()),
        version: 1,
        sign: '0.1',
        apiver: 1
    };
    u.host = host;
    u.AppName = "我的家园";
    u.apihost = apihost;


    function response(json, callback) {
        api.ajax(json, function (ret, err) {
            if (ret != undefined) {
                if (ret.StateCode == 2001) {
                    api.openWin({
                        name: 'login',
                        url: 'widget://html/login/login.html',
                        slidBackEnabled: false,
                    });
                    $api.rmStorage('localUserInfor');
                    $api.rmStorage('inviteImage');
                    $api.rmStorage('shopImage');
                    api.setPrefs({
                        key: 'isLogin',
                        value: 'false'
                    });
                    //u.exit();
                }
                callback(ret, err);
            } else {
                if (err.statusCode == 401) {
                    // toLogin()
                    // console.log('4444')
                    // api.openWin({
                    //     name: 'login',
                    //     url: './html/login/login.html',
                    //     delay: times,
                    //     slidBackType: 'edge',
                    //     vScrollBarEnabled: false,
                    //     slidBackEnabled: false,
                    // })
                }
                $common.closeProgress();
                $common.toast(JSON.stringify(err));
            }

        });
    }

    function parseArguments(url, json, fnSuc, method) {
        if (method == undefined) {
            method = 'post';
        }
        json.url = url
        // typeof 返回值有六种可能： "number," "string," "boolean," "object," "function," 和 "undefined."
        if ((json != undefined) && (typeof (json) != 'function')) {
            data = json;
            if (json.url == undefined) {
                data.url = defaultRequest.url;
            }
            if (json.method == undefined) {
                data.method = method;
            }
            if (json.dataType == undefined) {
                data.dataType = 'json';
            }
        }
        // alert(json.url)
        return {
            data: data,
            callback: fnSuc
        };
    }

    u.request = function () {
        var argsToJson = parseArguments.apply(null, arguments);
        var url = argsToJson.url;
        var json = argsToJson.data;
        var fnSuc = argsToJson.callback;
        if (u.judgeNetwork()) {
            response(json, fnSuc);

        } else {
            api.hideProgress()
        }
    };
    u.isLogin = function (callback) {
        var back = {};
        api.getPrefs({
            key: 'isLogin'
        }, function (ret, err) {
            if (ret && ret.value == 'true') {
                back.value = true;
                callback(back);
                // else{back.value = false;callback(back);}
            } else {

                back.value = false;
                callback(back);
            }
        });
    };
    u.exit = function () {
        $api.rmStorage('localUserInfor');
        api.setPrefs({
            key: 'isLogin',
            value: 'false'
        });
        //刷新免费使用列表
        api.sendEvent({
            name: 'freeRefresh',
            extra: {
                msg: ""
            }
        });
    };
    u.clipText = function (key, msg) {
        clipBoard = api.require('clipBoard');
        clipBoard.set({
            value: key
        }, function (ret, err) {
            if (ret) {
                $common.toast(msg);
            } else {
                alert(JSON.stringify(err));
            }
        });
    }
    u.FormatJsonData = function (date) {
        date = date.replace("T", " ").split(".")[0]
        return date;
    }
    //计算时间差（距离当前时间）
    u.timeDiffer = function (endDate) {
        //var date1= '2018-08-17 00:00:00';  //结束时间
        var date1 = endDate.replace("-", "/").replace("-", "/");  //结束时间
        var date2 = new Date();    //开始时间
        var date3 = new Date(date1).getTime() - date2.getTime();   //时间差的毫秒数

        //计算出相差天数
        var days = Math.floor(date3 / (24 * 3600 * 1000))

        //计算出小时数

        var leave1 = date3 % (24 * 3600 * 1000)    //计算天数后剩余的毫秒数
        var hours = Math.floor(leave1 / (3600 * 1000))
        //计算相差分钟数
        var leave2 = leave1 % (3600 * 1000)        //计算小时数后剩余的毫秒数
        var minutes = Math.floor(leave2 / (60 * 1000))
        //计算相差秒数
        var leave3 = leave2 % (60 * 1000)      //计算分钟数后剩余的毫秒数
        var seconds = Math.round(leave3 / 1000)
        return {day: days, hour: hours, minute: minutes, second: seconds}
        //alert(" 相差 "+days+"天 "+hours+"小时 "+minutes+" 分钟"+seconds+" 秒")
    }
    //格式化图片链接
    u.formatImgUrl = function (url) {
        var http = url.indexOf("http");
        if (http >= 0) {
            return url;
        } else {
            return "http:" + url;
        }
    }
    u.closeLoginWin = function () {
        var type = 1;
        if (api.winName == 'root') {
            type = 0;
        } else if (api.pageParam == undefined) {
            type = 1;
        } else if (api.pageParam.type == undefined) {
            type = 1;
        } else {
            type = api.pageParam.type;
        }

        switch (type) {
            case 0: //通过原生activity打开的登录页面（root是登录页面）
                api.closeWin();
                // u.closeAllWin();
                break;
            case 1: //通过superWeb打开的登录页面
                api.closeWin();
                break;
            case 2: //例如：退出登录
                api.closeToWin({
                    name: 'root'
                });
                break;
            default:
                api.closeWin();
                break;
        }
    };
    u.openWin = function (name, Param) {
        api.getPrefs({
            key: 'isLogin'
        }, function (ret, err) {
            if (ret && ret.value == 'true') {
                api.openWin({
                    name: name,
                    url: 'widget://html/' + name + '.html',
                    pageParam: Param
                });
            } else {
                $common.toast("请先登录")
                api.openWin({
                    name: 'login_qsj',
                    url: 'widget://html/login/login.html',
                    slidBackEnabled: false,
                });
            }
        });

    }
    u.openUrlWin = function (name, Param) {
        api.getPrefs({
            key: 'isLogin'
        }, function (ret, err) {
            if (ret && ret.value == 'true') {
                api.openWin({
                    name: name,
                    url: 'widget://html/' + name + '.html',
                    // useWKWebView:true,
                    pageParam: Param
                });
            } else {
                $common.toast("请先登录")
                api.openWin({
                    name: 'login_qsj',
                    url: 'widget://html/login/login.html',
                    slidBackEnabled: false,
                });
            }
        });
        // api.openWin({
        //     name: name,
        //     url: 'widget://html/' + name + '.html',
        //     pageParam: Param
        // });

    }

    u.openNewWin = function (name, Param) {
        api.openFrame({
            name: name,
            url: Param.url,
            pageParam: Param,
            reload: true,
            // useWKWebView:true,
            rect: {
                x: 0,
                y: 60,
                w: 'auto',
                h: 'auto'
            }
        });

    }
    u.openFrame = function (name, url) {
        api.openFrame({
            name: name,
            url: url,
            rect: {
                x: 0,
                y: 0,
                w: api.winWidth,
                h: api.winHeight
            },
            pageParam: {
                name: 'test'
            },
            bounces: false,
            bgColor: 'rgba(0,0,0,0)',
            vScrollBarEnabled: true,
            hScrollBarEnabled: true
        });

    }
    u.closeWin = function (name) {
        api.closeWin({
            name: name
        });
    }
    u.closeSelfWin = function () {
        api.closeWin();
    }
    u.closeFrame = function (name) {
        api.closeFrame({
            name: name
        });
    }
    u.toast = function (msg) {
        api.toast({
            msg: msg,
            duration: 3000,
            location: 'center'
        });
    }
    // var load;
    u.progress = function (msg) {
        var toast = new auiToast();
        toast.loading({
            title: "",
            duration: 2000
        }, function (ret) {
        });
        // msg = msg == undefined ? "加载中..." : msg;
        //  load = layer.load(1);
    }
    u.closeProgress = function () {
        var toast = new auiToast();
        toast.hide();
        //layer.close(load);
        // var uiloading = api.require('UILoading');
        // uiloading.closeFlower({
        //       id: u.aa
        //   });
    }
    u.alert = function (data) {
        api.alert({
            title: '提示',
            msg: data,
        }, function (ret, err) {
        });
    }
    //  下拉刷新
    u.setrefresh = function (func) {
        api.setRefreshHeaderInfo({
            visible: true,
            //loadingImg: 'widget://image/refresh1.png',
            bgColor: '#fff',
            textColor: '#999',
            textDown: '下拉刷新...',
            textUp: '松开刷新...',
            showTime: true
        }, function (ret, err) {
            func(ret, err);
        });

    }
    // 计算头部和内容区域高度
    u.fixHeader = function () {
        // var header = $api.dom('header');
        // // $api.css(header,'background:#333333');
        // $api.fixStatusBar(header);
        // var headerH = $api.offset(header).h;
        // var systemType = api.systemType;
        // return headerH;
        var header = $api.dom('header');
        // $api.css(header,'background:#333333');
        var headerH = 0;

        var systemType = api.systemType;
        $api.fixStatusBar(header);
        headerH = $api.offset(header).h;
        // if (systemType == 'ios') {
        //     $api.fixStatusBar(header);
        //     headerH = $api.offset(header).h;
        // }
        // else {
        //     headerH = $api.offset(header).h;
        // }
        return headerH;
    }
    // 打开外部链接
    u.openOutLink = function (url, name) {
        if (name == undefined) {
            name = '外部链接';
        }
        api.openWin({
            name: 'outlink',
            url: '../win/outlink.html',
            pageParam: {
                name: name,
                url: url
            }
        });
    }
    u.tag = function (status) {
        var html = '';
        html += '<div class="tag">';
        if (status == 1) {
            html += '<div class="car"></div>';
        }
        html += '<div class="scrolltop"></div>';
        html += '</div>';
        $('.tag').remove();
        $("body").append(html);
        $(".car").on('click', function () {
            $handsome.openShopCar();
        })
        $(".scrolltop").on('click', function () {
            $(window).scrollTop(0);
        })
        $(window).scroll(function () {
            if ($(window).scrollTop() != 0) {
                $(".tag").addClass('active');
            } else {
                $(".tag").removeClass('active');
            }
        })
    }
    u.swipe = {
        default_x: 0, //偏移起点
        default_y: 0,
        move_x: 0, //单次偏移量
        end_x: 0, //默认实际偏移
        status: true, //临界状态
        last_x: 0,
        step: 200, //动画滑动步长
        start_val: 100, //动画滑动开始值
        width: 0,
        winW: 0,
        allowLen: 0,
        move: function (el) {
            var self = this;
            el.on('touchmove', function (event) {
                event.preventDefault();
                if (self.default_y - event.targetTouches[0].pageY > 30 || self.default_y - event.targetTouches[0].pageY < -30) {
                    $(this).off('touchmove');
                    $(this).off('touchend');
                    // 向上滑动超过50则移除此事件,以便页面能继续滚动
                }

                self.move_x = -(self.default_x - event.targetTouches[0].pageX); //单次偏移量（相对）
                self.last_x = self.move_x + self.end_x; //实际x偏移量
                if (self.move_x > 0) {
                    /*向右移动*/
                    self.status = true;
                    if (self.last_x >= 0) {
                        self.last_x = 0;
                        self.end_x = 0;
                        self.status = false;
                    }
                } else if (self.move_x < 0) {
                    /*向左移动*/
                    self.status = true;
                    if (self.last_x <= self.allowLen) {
                        self.last_x = self.allowLen;
                        self.end_x = self.allowLen;
                        self.status = false;
                    }
                }

                el.removeAttr('style');
                el.css("margin-left", self.last_x + 'px');
                //                  console.log('当前偏移'+self.move_x);


            })
        },
        start: function (el) {
            var self = this;
            el.on('touchstart', function (event) {
                // alert(JSON.stringify(event.targetTouches[0].pageX));

                self.default_x = event.targetTouches[0].pageX;
                self.default_y = event.targetTouches[0].pageY;
                self.move(el);
                self.end(el);
            })
        },
        end: function (el) {
            var self = this;
            el.on('touchend', function (event) {
                if (self.status && self.move_x != 0) {
                    self.end_x = self.end_x + self.move_x;
                    if (parseInt(self.move_x) <= self.start_val) {
                        if (self.move_x > 0) {
                            self.end_x = self.end_x + self.step;
                        } else {
                            self.end_x = self.end_x - self.step;
                        }

                        if (self.end_x <= self.allowLen) {
                            self.end_x = self.allowLen;
                        }
                        if (self.end_x >= 0) {
                            self.end_x = 0;
                        }
                        el.css({
                            "transition": ".4s linear",
                            "margin-left": self.end_x + "px"
                        });
                    }
                    //                      console.log('实际偏移'+self.end_x);
                } else {
                    //                      console.log('临界值'+self.end_x);
                }

            })
        },
        ev: function (el, width) {
            this.width = width,
                this.winW = window.screen.width,
                this.allowLen = this.winW - this.width,
                this.start(el);
        }
    }
    u.checkUrl = function (str_url) {
        var strRegex = "^((https|http|ftp|rtsp|mms)?://)" +
            "?(([0-9a-z_!~*'().&=+$%-]+: )?[0-9a-z_!~*'().&=+$%-]+@)?" //ftp的user@
            +
            "(([0-9]{1,3}\.){3}[0-9]{1,3}" // IP形式的URL- 199.194.52.184
            +
            "|" // 允许IP和DOMAIN（域名）
            +
            "([0-9a-z_!~*'()-]+\.)*" // 域名- www.
            +
            "([0-9a-z][0-9a-z-]{0,61})?[0-9a-z]\." // 二级域名
            +
            "[a-z]{2,6})" // first level domain- .com or .museum
            +
            "(:[0-9]{1,4})?" // 端口- :80
            +
            "((/?)|" // a slash isn't required if there is no file name
            +
            "(/[0-9a-z_!~*'().;?:@&=+$,%#-]+)+/?)$";
        var re = new RegExp(strRegex);
        //re.test()
        if (re.test(str_url)) {
            return (true);
        } else {
            return (false);
        }
    }
    // 搜索记录
    u.searchHistory = function (str) {
        var history = $api.getStorage('history');
        if (history == undefined) {
            history = [];
        }
        for (var i = 0; i < history.length; i++) {
            if (history[i].name == str) {
                history.splice(i, 1);
            }
        }
        history.unshift({
            name: str
        });
        $api.setStorage('history', history);
        return history;
    }
    //设置顶部颜色
    u.setTopColor = function (tag) {
        if (api.systemType == 'ios') {
            tag.style.background = '#fdfdfd';
        } else {
            tag.style.background = '#333333';
        }
    }
    u.closeSharePopup = function () {
        popup.hide($api.dom("#bottom"))
    }
    u.openSharePopup = function () {
        popup.show($api.dom("#bottom"))
    }
    u.shareWx = function (url, title, type, description, img, callback) {
        popup.hide($api.dom("#bottom"))
        var wx = api.require('wx');
        wx.shareWebpage({
            scene: 'session',
            title: title,
            description: description,
            thumb: img,
            contentUrl: url
        }, function (ret, err) {
            callback(ret)
        });
    }
    u.shareQQ = function (url, title, type, description, img, callback) {
        popup.hide($api.dom("#bottom"))
        var qq = api.require('qq');
        qq.shareNews({
            url: url,
            title: title,
            type: type,
            description: description,
            imgUrl: img
        }, function (ret, err) {
            callback(ret, err)
        });
    }
    u.GetClipText = function (callback) {
        clipBoard = api.require('clipBoard');
        clipBoard.get(function (ret, err) {
            callback(ret, err)
        });
    }
    //分享
    //内容url 标题  描述  图片

    u.share = function (url, title, description, img, type) {
        var s = '<div id="share">\
                <div class="share-out">\
                    <div class="share-content">\
                        <div class="s_row" id="qq">\
                            <div class="sicon s-qq"></div>发送到QQ\
                        </div>\
                        <div class="s_row" id="wechat">\
                            <div class="sicon s-wechat"></div>发送到微信\
                        </div>\
                        <div class="s_row" id="friend">\
                            <div class="sicon s-friend"></div>发送到微信朋友圈\
                        </div>\
                        <div class="s_row" id="qzone">\
                            <div class="sicon s-qzone"></div>发送到QQ空间\
                        </div>\
                    </div>\
                </div>\
                <div id="s_close">\
                </div>\
            </div>';
        $("body").append(s);
        $("#s_close,#share").click(function () {
            $("#share").remove();
        })
        var qq = api.require('qq');
        var wx = api.require('wx');

        //     QQ分享
        $("#qq").click(function (e) {
            e.stopPropagation();
            qq.shareNews({
                url: url,
                title: title,
                type: 'QFriend',
                description: description,
                imgUrl: img
            }, function (ret) {
                if (ret.status == true) {
                    u.toast('分享成功');
                    u.shareType(type);
                }

            });
        })
        //     空间分享
        $("#qzone").click(function (e) {
            e.stopPropagation();
            qq.shareNews({
                url: url,
                title: title,
                type: 'QZone',
                description: description,
                imgUrl: img
            }, function (ret) {
                if (ret.status == true) {
                    u.toast('分享成功');
                    u.shareType(type);
                }

            });
        })
        //     微信分享
        $("#wechat").click(function (e) {
            e.stopPropagation();
            api.imageCache({
                url: img
            }, function (ret, err) {
                wx.shareWebpage({
                    scene: 'session',
                    title: title,
                    description: description,
                    thumb: ret.status ? ret.url : 'widget://image/log.png',
                    contentUrl: url
                }, function (ret, err) {
                    if (ret.status) {
                        u.toast('分享成功');
                        u.shareType(type);
                    }
                });
            });
        })
        //     朋友圈分享
        $("#friend").click(function (e) {
            e.stopPropagation();

            api.imageCache({
                url: img
            }, function (ret, err) {
                wx.shareWebpage({
                    scene: 'timeline',
                    title: title,
                    description: description,
                    thumb: ret.status ? ret.url : 'widget://image/log.png',
                    contentUrl: url
                }, function (ret, err) {
                    if (ret.status) {
                        u.toast('分享成功');
                        u.shareType(type);
                    }
                });
            });
        })

    }

    u.parseXML = function (data) {
        var xml, tmp;
        try {
            if (window.DOMParser) { // Sandard
                tmp = new DOMParser();
                xml = tmp.parseFromString(data, "text/xml");
            } else { //IE
                xml = new ActiveXObject("Microsoft.XMLDOM");
                xml.async = "false";
                xml.loadXML(data);
            }
        } catch (e) {
            xml = undefined;
        }
        if (!xml || !xml.documentElement || xml.getElementsByTagName("parsererror").length) {
            jQuery.error("Invalid XML: " + data);
        }
        return xml;
    }

    u.screenShot = function (fn) {
        var screenClip = api.require('screenClip');
        screenClip.open({
            cutFrame: {
                x: 0,
                y: 50,
                w: api.winWidth,
                h: api.winHeight
            }
        })
        screenClip.save({
            album: false,
            imgPath: 'widget://image/',
            imgName: 'clip.png'
        }, function (ret, err) {
            fn(ret.status)
        })
        // screenClip.screenShot({
        // album:false,imgPath:'widget://image/',imgName:'clip.png'
        // },function(ret, err) {
        //  fn(ret.status);
        // });
    }


    /*ios上先关闭再打开 ！！！
               android中先打开在关闭！！！*/
    u.judgeNetwork = function () {
        var connectionType = api.connectionType; //比如： wifi
        if ('none' == connectionType) {
            u.toast('请检查网络连接!');
            return false;
        } else {
            return true;
        }
        // unknown            //未知
        // ethernet        //以太网
        // wifi            //wifi
        // 2g                //2G网络
        // 3g                //3G网络
        // 4g                //4G网络
        // none            //无网络
    };
    u.showLoading = function () {
        document.getElementById("load5").style.display = "block";
    }
    u.hideLoading = function () {
        document.getElementById("load5").style.display = "none";
    }
    u.keyfilter = function (keywords, fn) {
        api.ajax({
            url: 'https://suggest.taobao.com/sug?callback=jQuery112407101364103693755_1493091381962&code=utf-8&q=' + keywords + '&_=1493091382026&isg=AhIS9EuknlO9x-IItIQuYl8EY9jAegP4j7MAQNxviEWw77Tp87EozUzJKfyp&isg2=ApycFeNQSNeAz0PnLCyAid%2Fh7LBKo0A%2F&qq-pf-to=pcqq.group',
            method: 'get',
            data: {
                values: {}
            },
            dataType: 'text'
        }, function (ret, err) {
            var result = ret.replace('\r\n', '');
            var r = result.match(/[(]{1}(.*?)[)]{1}/);
            fn(JSON.parse(r[1]).result);
        });
    }
    u.outopen = function (param) {
        //          var id = ret.id;
        //            var title = ret.title;
        //            var content = ret.content;
        //            var extra = ret.extra;
        if (param.page) {
            if (param.page.indexOf("http") != -1) {
                u.openWin('thirdHead_qsj', {
                    title: '',
                    key: "OutUrl",
                    FrameName: param.page
                });
                return;
            }
            switch (param.page) {
                case 'order': //打开订单页面
                    u.openUrlWin('orderHead_qsj', {
                        title: '我的订单',
                        FrameName: 'order',
                        openUrl: 'widget://html/my/order_qsj.html'
                    });
                    break;
                default:
                    break;
            }
        }
    };
    // 图片本地路径转换成base64格式
    u.base64Url = function (imgUrl, fn) {
        var trans = api.require('trans');
        trans.decodeImgToBase64({
            imgPath: imgUrl
        }, function (rets, errs) {
            if (rets.status) {
                fn(rets.base64Str);
            } else {
                $common.toast(JSON.stringify(errs));
            }
        })
    };
    u.multiGraphSharing = function (imgs) {
        var shareAction = api.require("shareAction");
        var wx = api.require("wx");
        var imgList = [];
        var share = function () {
            $common.closeProgress();
            api.hideProgress();
            if (api.systemType == 'ios') {
                // u.multiGraphSharingAndroid(imgs);
                shareAction.share({
                    text: '',
                    type: 'image',
                    images: imgList
                });
            } else {
                // wx.shareMutableImg({
                //     imgs: imgList
                // });
                wx.shareImage({
                    scene: 'timeline',
                    contentUrl: imgList[0]
                }, function (ret, err) {
                    if (ret.status) {
                        $common.toast('分享成功');
                    }
                });
            }
        }
        if (typeof (imgs) == 'object') {
            for (var i in imgs) {
                imgs[i] = imgs[i].replace('.webp', '');
                api.imageCache({
                    url: imgs[i],
                    thumbnail: false,
                }, function (ret, err) {
                    if (ret.status) {
                        imgList.push(ret.url);
                        if (imgList.length === imgs.length) {
                            share();
                        }
                    }
                })
            }
        } else if (typeof (imgs) == 'string') {
            imgs = imgs.replace('.webp', '');
            api.imageCache({
                url: imgs,
                thumbnail: false,
            }, function (ret, err) {
                if (ret.status) {
                    imgList.push(ret.url);
                    share();
                }
            })
        }
    }
    u.multiGraphSharingAndroid = function (imgs) {  //安卓分享多图
        var tools = api.require("tools");  //var dir = api.wgtRootDir;
        var imgList = [], img = '';
        for (var i in imgs) {
            api.imageCache({
                url: imgs[i],
                thumbnail: false,
            }, function (ret, err) {
                if (ret.status) {
                    img = "file://" + ret.url
                    imgList.push(img);
                    if (imgList.length === imgs.length) {
                        share(imgList);
                    }
                }
            })
        }
        var share = function (imgList) {
            api.systemType == 'ios'
            param = {
                picurl: imgList,
                to: "system",
                content: "",    //【在吗？不再滚】
                show_dialog: true,
            };
            $common.closeProgress();
            api.hideProgress();
            tools.share(param, function (res) {
            });
        }
    }
    u.wxShareImage = function (url) { // 微信分享单图
        var wx = api.require('wx');
        api.imageCache({
            url: url,
            thumbnail: false
        }, function (ret, err) {
            if (ret.status) {
                wx.shareImage({
                    scene: 'session',
                    contentUrl: ret.url
                }, function (ret, err) {
                    if (ret.status) {
                        $common.toast('分享成功');
                    }
                });
            }
        })
    }
    u.setGoodsImage = function (imgUrl) {
        var index1 = imgUrl.indexOf("gchat.qpic.cn"); //qq采集
        var index2 = imgUrl.indexOf("img14.360buyimg"); //京东采集
        var index3 = imgUrl.indexOf("jingtuitui.com"); //京推推采集
        var index4 = imgUrl.indexOf("alicdn.com"); // 阿里
        var index5 = imgUrl.indexOf("quanshuojia.oss-cn-beijing.aliyuncs.com"); // oss
        var http = imgUrl.indexOf("http");
        if (api.systemType = "ios") {
            if (imgUrl.indexOf(".webp") >= 0) {
                imgUrl = imgUrl.replace(".webp", '')
            }
        }
        if (http < 0) {
            imgUrl = "https:" + imgUrl;
        }

        if (index1 > 0) {
            return imgUrl + "200/200"
        } else if (index2 > 0) {
            return imgUrl.replace('img14.360buyimg.com/imgzone', 'img14.360buyimg.com/n7')
        } else if (index3 > 0) {
            return imgUrl
        } else if (index4 > 0) {
            return imgUrl + "_200x200"
        } else if (index5 > 0) {
            return imgUrl + "_200"
        } else {
            return imgUrl
        }


    };
    //计算预估赚 升级赚
    u.formula = function (LastPrice, TKMoneyRate, type) {
        //type 1淘宝 2京东 3拼多多
        var LastPrice = parseFloat(LastPrice);
        var TKMoneyRate = parseFloat(TKMoneyRate);
        var formula = $api.getStorage('formula');
        var UpTB = parseFloat(formula.tbUpgradeIncome);
        var eTB = parseFloat(formula.tbExpectedIncome);
        var UpJD = parseFloat(formula.jdUpgradeIncome);
        var eJD = parseFloat(formula.jdExpectedIncome);
        var UpPDD = parseFloat(formula.pddUpgradeIncome);
        var ePDD = parseFloat(formula.pddExpectedIncome);
        type = String(type);
        switch (type) {
            case "1":
                return {
                    eIncome: (LastPrice * (TKMoneyRate / 100) * eTB).toFixed(2),
                    uIncome: (LastPrice * (TKMoneyRate / 100) * UpTB).toFixed(2)
                }
                break;
            case "2":
                return {
                    eIncome: (LastPrice * (TKMoneyRate / 100) * eJD).toFixed(2),
                    uIncome: (LastPrice * (TKMoneyRate / 100) * UpJD).toFixed(2)
                }
                break;
            case "3":
                return {
                    eIncome: (LastPrice * (TKMoneyRate / 100) * ePDD).toFixed(2),
                    uIncome: (LastPrice * (TKMoneyRate / 100) * UpPDD).toFixed(2)
                }
                break;
            default:

        }
    };
    //格式化文本（去掉标签）
    u.formalText = function (html) {
        var dd = html.replace(/<\/?.+?>/g, "");
        var dds = dd.replace(/ /g, "");//dds为得到后的内容
        return dds;
    };
    //格式化时间
    u.transDate = function (dateTimeStamp) {
        dateTimeStamp = Date.parse(dateTimeStamp.replace(/-/gi, "/"));
        var minute = 1000 * 60;
        var hour = minute * 60;
        var day = hour * 24;
        var halfamonth = day * 15;
        var month = day * 30;
        var now = new Date().getTime();
        var diffValue = now - dateTimeStamp;
        if (diffValue < 0) {
            return;
        }
        var monthC = diffValue / month;
        var weekC = diffValue / (7 * day);
        var dayC = diffValue / day;
        var hourC = diffValue / hour;
        var minC = diffValue / minute;
        if (monthC >= 1) {
            result = "" + parseInt(monthC) + "月前";
        } else if (weekC >= 1) {
            result = "" + parseInt(weekC) + "周前";
        } else if (dayC >= 1) {
            result = "" + parseInt(dayC) + "天前";
        } else if (hourC >= 1) {
            result = "" + parseInt(hourC) + "小时前";
        } else if (minC >= 1) {
            result = "" + parseInt(minC) + "分钟前";
        } else
            result = "刚刚";
        return result;
    };
    //时间戳转为日期格式
    u.timestampToTime = function (timestamp) {
        var date = new Date(timestamp * 1000);//时间戳为10位需*1000，时间戳为13位的话不需乘1000
        var Y = date.getFullYear() + '-';
        var M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1) + '-';
        var D = date.getDate() + ' ';
        var h = date.getHours() + ':';
        var m = date.getMinutes() + ':';
        var s = date.getSeconds();
        return Y + M + D;
    };
    //智能搜索
    u.openSuperSearch = function (self) {
        var type;
        self ? type = "self" : type = '';
        var clipBoard = api.require('clipBoard');
        clipBoard.get(function (ret, err) {
            if (ret) {
                var title = ret.value;
                if (title.length > 10) {
                    api.openFrame({
                        name: 'dialog',
                        url: 'widget://html/master/dialog_qsj.html',
                        rect: {
                            x: 0,
                            y: 0,
                            w: api.winWidth,
                            h: api.winHeight
                        },
                        bgColor: 'rgba(0,0,0,0.6)',
                        bounces: false,
                        pageParam: {
                            title: title,
                            self: type,
                        }
                    });
                }
            } else {
                //alert(JSON.stringify(err));
            }
        });
    };
    //未来时间与当前时间差
    u.getTimeDay = function (date1) {
        // var date1=new Date();  //开始时间
        var date2 = new Date();    //结束时间
        var date3 = date2.getTime() - date1.getTime()  //时间差的毫秒数


        //计算出相差天数
        var days = Math.floor(date3 / (24 * 3600 * 1000))

        //计算出小时数

        var leave1 = date3 % (24 * 3600 * 1000)    //计算天数后剩余的毫秒数
        var hours = Math.floor(leave1 / (3600 * 1000))
        //计算相差分钟数
        var leave2 = leave1 % (3600 * 1000)        //计算小时数后剩余的毫秒数
        var minutes = Math.floor(leave2 / (60 * 1000))


        //计算相差秒数
        var leave3 = leave2 % (60 * 1000)      //计算分钟数后剩余的毫秒数
        var seconds = Math.round(leave3 / 1000)

        return {day: days, hour: hours, minute: minutes, second: seconds}
        alert(" 相差 " + days + "天 " + hours + "小时 " + minutes + " 分钟" + seconds + " 秒")
    }
    // 分享单图到微信、朋友圈
    u.shareModule = function (arr) {
        var dialogBox = api.require('dialogBox');
        var wx = api.require('wx');
        if (!arr || arr.length < 1) {
            $common.toast('请选择分享图片');
            return;
        }
        dialogBox.actionMenu({
            rect: {
                h: 150
            },
            items: [
                {
                    text: '微信',
                    icon: 'widget://image/share2_qsj.png'
                }, {
                    text: '朋友圈',
                    icon: 'widget://image/share3_qsj.png'
                }
            ],
            styles: {
                bg: '#FFF',
                column: 2,
                itemText: {
                    color: '#000',
                    size: 12,
                    marginT: 12
                },
                itemIcon: {
                    size: 60
                }
            },
            tapClose: true
        }, function (ret) {
            if (ret.index == 0) {
                api.imageCache({
                    url: arr[0],
                    thumbnail: false
                }, function (ret, err) {
                    if (ret.status) {
                        wx.shareImage({
                            scene: 'session',
                            contentUrl: ret.url
                        }, function (ret, err) {
                            if (ret.status) {
                                alert('分享成功');
                            }
                        });
                    }
                })
            } else if (ret.index == 1) {
                api.imageCache({
                    url: arr[0],
                    thumbnail: false
                }, function (ret, err) {
                    if (ret.status) {
                        wx.shareImage({
                            scene: 'timeline',
                            contentUrl: ret.url
                        }, function (ret, err) {
                            if (ret.status) {
                                alert('分享成功');
                            }
                        });
                    }
                })
            }
        })
    },
        //ios审核开关
        u.getiosCheck = function (callback) {
            if (api.systemType == 'android') {
                callback(1);
            } else {
                //callback(1);
                $common.request('CommonApi/GetAppToExamine', {}, function (ret, err) {
                    // console.log(JSON.stringify(ret));
                    if (ret.StateCode == 1) {
                        if (ret.Data == 0) {  //0开启审核配置  1 关闭审核配置
                            $api.setStorage('iosCheck', 0);
                        } else {
                            $api.setStorage('iosCheck', 1);
                        }
                        // alert($api.getStorage('iosCheck'))
                        callback($api.getStorage('iosCheck'));
                    }
                })
            }
        },
        window.$common = u;
})(window)
